package br.com.nooclix.salon.controller;

import br.com.nooclix.salon.application.EmployeeApplication;
import br.com.nooclix.salon.controller.util.ResponseData;
import br.com.nooclix.salon.domain.employee.Employee;
import br.com.nooclix.salon.infrastructure.util.ApplicationContextRegister;
//Essa classe é responsável por fazer a conexão do Java com o blazeDS
public class EmployeeController {
	private EmployeeApplication employeeApplication = ApplicationContextRegister
			.getBean("employeeApplication", EmployeeApplication.class);

	public ResponseData persist(Employee employee) {
		ResponseData responseData = new ResponseData();

		try {
			
			// configurando para ser NULL por causa do FLEX ter padrao 0(ZERO)
			//Daí ele deixa a critério do banco criar as chaves
			employee.setCode(null);
			//Seta o Code de person
			employee.getPerson().setCode(null);
			//Seta o Code de address
			employee.getPerson().getAddress().setCode(null);
			//Seta o employeeApplication do XML, para indicar qual a entidade que irá usar com o spring
			employeeApplication.persist(employee);
			//Caso tenha dado certo, mostra a mensagem que está dentro de ResponseData.OK
			responseData.setStatus(ResponseData.OK);
			//Captura a exceção lançada e trata ela com o ResponseData.FAILED
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setMessage(e.getMessage());
			responseData.setStatus(ResponseData.FAILED);
		}

		return responseData;

	}

	public ResponseData update(Employee employee) {
		ResponseData responseData = new ResponseData();

		try {
			employeeApplication.update(employee);
			responseData.setStatus(ResponseData.OK);
		} catch (Exception e) {
			responseData.setMessage(e.getMessage());
			responseData.setStatus(ResponseData.FAILED);
		}

		return responseData;

	}

	public ResponseData remove(Employee employee) {
		ResponseData responseData = new ResponseData();

		try {
			employeeApplication.delete(employee);
			responseData.setStatus(ResponseData.OK);
		} catch (Exception e) {
			responseData.setMessage(e.getMessage());
			responseData.setStatus(ResponseData.FAILED);
		}

		return responseData;

	}

	public ResponseData findByName(String name) {
		ResponseData responseData = new ResponseData();

		try {
			responseData.setItems(employeeApplication.findByName(name));
			responseData.setStatus(ResponseData.OK);
		} catch (Exception e) {
			responseData.setMessage(e.getMessage());
			responseData.setStatus(ResponseData.FAILED);
		}

		return responseData;

	}

}
